import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

const routes = [
    {
        path: "/",
        redirect: "/blogs",
    },
    {
        path: "/login",
        component: () => import("../views/Login.vue"),
    },
    {
        path: "/register",
        component: () => import("../views/Register.vue"),
    },
    {
        path: "/blogs",
        component: () => import("../views/BlogList.vue"),
    },
    {
        path: "/blogs/add",
        component: () => import("../views/BlogAdd.vue"),
    },
    {
        path: "/blogs/edit/:id",
        component: () => import("../views/BlogEdit.vue"),
    },
    {
        path: "/blogs/detail/:id",
        component: () => import("../views/BlogDetail.vue"),
    },
];

const router = new VueRouter({
    mode: "history",
    base: process.env.BASE_URL,
    routes,
});

// 路由守卫
router.beforeEach((to, from, next) => {
    const token = window.sessionStorage.getItem("token");
    if (to.path === "/login" || to.path === "/register" || token) {
        next();
    } else {
        next("/login");
    }
});

export default router;
